package com.yupi.usercenter.service.impl;

import java.util.Date;
import java.util.List;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.yupi.usercenter.common.BaseResponse;
import com.yupi.usercenter.common.ErrorCode;
import com.yupi.usercenter.common.ResultUtils;
import com.yupi.usercenter.exception.BusinessException;
import com.yupi.usercenter.mapper.UserMapper;
import com.yupi.usercenter.model.domain.User;
import com.yupi.usercenter.service.UserService;

import java.util.Collections;

import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.stereotype.Service;
import org.springframework.util.DigestUtils;

import javax.servlet.http.HttpServletRequest;


/**
 * @author 31913
 * @description 针对表【user(用户)】的数据库操作Service实现
 * @createDate 2024-05-12 22:40:03
 */
@Slf4j
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements UserService {
    @Autowired
    private UserMapper userMapper;
    private final String salt = "yupi";

    //用户注册
    @Override
    public long userRegister(String userAccount, String userPassword, String checkPassword, String planetCode) {
        //1.判断参数是否为空
        if (StringUtils.isBlank(userAccount) || StringUtils.isBlank(userPassword) || StringUtils.isBlank(checkPassword) || StringUtils.isBlank(planetCode)) {
           throw new BusinessException(ErrorCode.NULL_ERROR, "参数不能为空");
        }
        //2.账户的长度不得小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账号的长度不符合规定");
        }
        //3.密码的长度不得小于8位
        if (userPassword.length() < 8 || checkPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码的长度不符合规定");
        }

        //4.账户不能含有特殊字符
        String validPattern = "^[a-zA-Z0-9]+$";
        if (!userAccount.matches(validPattern)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数类型错误");
        }
        //5.密码和校验密码相同
        if (!userPassword.equals(checkPassword)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码和确认密码不一致，请检查后再输入");
        }
        //5.星球编号的长度不得大于5位
        if (planetCode.length() > 5) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"星球编号的长度错误");
        }

        //6.账户不能重复,根据mybatis-plus的selectCount()方法查询数据库中该账户是否重复
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        Long count = userMapper.selectCount(queryWrapper);
        if (count > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "已存在该用户");
        }

        //6.星球编号不能重复
        queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("planetCode", planetCode);
        if (userMapper.selectCount(queryWrapper) > 0) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "已存在该用户");
        }
        //7.对密码进行加密，使用md5+salt进行加密
        String encryptPassword = DigestUtils.md5DigestAsHex((salt + userPassword).getBytes());
        //8.插入数据
        User user = new User();
        user.setUserAccount(userAccount);
        user.setUserPassword(encryptPassword);
        user.setPlanetCode(planetCode);

        boolean save = this.save(user);
        if (!save) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "插入数据失败");
        }
        return user.getId();
    }

    //登录
    @Override
    public User userLogin(String userAccount, String userPassword, HttpServletRequest request) {
        //1.判断参数是否为空
        if (StringUtils.isBlank(userAccount) || StringUtils.isBlank(userPassword)) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "参数不能为空");
        }
        //2.账户的长度不得小于4位
        if (userAccount.length() < 4) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "账户的长度不符合规定");
        }
        //3.密码的长度不得小于8位
        if (userPassword.length() < 8) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR,"密码的长度不符合规定");
        }

        //4.账户不能含有特殊字符
        String validPattern = "^[a-zA-Z0-9]+$";
        if (!userAccount.matches(validPattern)) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "参数类型错误");
        }
        //5.向数据库查询用户是否存在
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq("userAccount", userAccount);
        User user = userMapper.selectOne(queryWrapper);
        if (user == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "未查询到此用户");
        }
        //6.密码进行加密，使用md5+salt进行加密

        String encryptPassword = DigestUtils.md5DigestAsHex((salt + userPassword).getBytes());
        //7.比较密码是否相同
        QueryWrapper<User> userQueryWrapper = new QueryWrapper<>();
        //逻辑删除为0的情况下才能查询
        userQueryWrapper.eq("isDelete", 0);
        userQueryWrapper.eq("userAccount", userAccount);
        queryWrapper.eq("userPassword", encryptPassword);
        if (userMapper.selectOne(userQueryWrapper) == null) {
           throw new BusinessException(ErrorCode.PARAMS_ERROR,"查询不到该用户");
        }
        //8.登录成功
        log.info("用户登录成功");
        //8.1.用户脱敏
        User safeUser = new User();
        safeUser.setId(user.getId());
        safeUser.setUsername(user.getUsername());
        safeUser.setUserAccount(user.getUserAccount());
        safeUser.setAvatarUrl(user.getAvatarUrl());
        safeUser.setGender(user.getGender());
        safeUser.setPhone(user.getPhone());
        safeUser.setEmail(user.getEmail());
        safeUser.setPlanetCode(user.getPlanetCode());
        safeUser.setUserStatus(user.getUserStatus());
        safeUser.setCreateTime(user.getCreateTime());
        //8.2.在session中保存用户信息
        request.getSession().setAttribute("userId", safeUser);
        return safeUser;

    }

    //搜索用户
    @Override
    public List<User> searchUserByName(String username) {
        //1.判断参数是否为空
        if (StringUtils.isBlank(username) || username.isEmpty()) {
            throw new BusinessException(ErrorCode.NULL_ERROR, "参数不能为空");
        }

        //2.继续执行搜索
        QueryWrapper<User> queryWrapper = new QueryWrapper<>();
        queryWrapper.like("username", username);
        List<User> userList = userMapper.selectList(queryWrapper);
        if (userList != null) {
            return userList;
        }
        log.info("用户不存在");
        throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户不存在");
    }

    @Override
    public int userLogout(HttpServletRequest request) {
        if (request.getSession().getAttribute("userId") != null) {
            request.getSession().removeAttribute("userId");
            return 1;
        }
        log.info("用户未登录");
        throw new BusinessException(ErrorCode.PARAMS_ERROR, "用户未登录");
    }
}




